from flask import g
from flask_restful import Resource
from flask_restful.reqparse import RequestParser
from comment.utils.decorators import login_required
from comment.modules.product import Product
from comment.modules.product_rate import Product_rate
from comment.modules.deal_record  import DealRecord
from comment.modules import db
from financial.resources.transaction.serializer import DealRecordPaginateSerializer
from comment.modules.user import User


class Deal_Resource(Resource):
    '''交易记录的资源类'''

    def get(self):
        '''
        投资记录的列表
        :return:
        '''
        rp =RequestParser()
        rp.add_argument('start')#起始时间
        rp.add_argument('end')#结束时间
        rp.add_argument('deal_type')#交易类型  初始值 0
        rp.add_argument('curPage',required=True)#当前页号
        rp.add_argument('per_page',required=True)#每页显示的条数
        args =rp.parse_args()
        start =args.get('start')
        end =args.get('end')
        deal_type =0 if args.get('deal_type') ==None else int(args.get('deal_type'))
        curPage =  int(args.get('curPage'))
        pageSize =int(args.get('per_page'))

        uid = g.user_id
        user = User.query.filter(User.id==uid).first()
        q = DealRecord.query#得到一个查询对象

        #开始过滤  第一个过滤 根据交易的类型过滤
        if deal_type>0:
            q = q.filter(DealRecord.aType==deal_type)

        #第二个过滤 根据用户id  (当前用户如果是管理员  可以查询别人的  否则只可以查询自己的)
        if user.role == 0:
            q = q.filter(DealRecord.aUserId==uid)

        #第三个过滤   过滤时间
        if start and end:
            q = q.filter(db.cast(DealRecord.aDate,db.DATE)>=db.cast(start,db.DATE)).filter(db.cast(DealRecord.aDate,db.DATE)<=db.cast(end,db.DATE))
        data = q.paginate(curPage, pageSize, error_out=False)
        data =DealRecordPaginateSerializer(data).to_dict()
        return {'msg':'success','data':data}

